<template>
  <div class="app-container">
    <div v-show="type == 0 || type == 2">
      <el-row>
<!--        <el-col :span="4" style="margin-left: -20px;">-->
<!--          <MainType :typeCode="typeCode" @getNode="getNode" :isTree="isTree"></MainType>-->
<!--        </el-col>-->
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch"
                   label-width="100px">
            <el-form-item size="mini" label="企业名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable
                        @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="企业地址" prop="enterpriseAddress">
              <el-input v-model="queryParams.enterpriseAddress" placeholder="请输入企业地址" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item> -->
            <el-form-item size="mini" label="企业性质" prop="enterpriseNature">
              <el-select v-model="queryParams.enterpriseNature" placeholder="请选择企业性质" style="width:150px">
                <el-option v-for="dict in dict.type.enterprise_nature" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item size="mini" label="所属行业" prop="industry">
              <el-select v-model="queryParams.industry" placeholder="请选择所属行业" style="width:150px">
                <el-option v-for="dict in dict.type.customer_industry" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8" v-if="markAs == null">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="editMainClass">修改主分类</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="userShow(1)">修改业务经理</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>
          <el-row :gutter="10" class="mb8" v-else>
            <el-col :span="1.5">
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button @click="cancel">关 闭</el-button>
            </el-col>
          </el-row>
          <el-table size="mini" height="450" :row-style="{ height: '30px' }" border :cell-style="{ padding: '0px' }"
                    ref="table" v-loading="loading" @selection-change="handleSelectionChange" @row-click="handleCurrentChange"
                    :data="infoList" :class="{ 'no-multiple': markAs != null }" :row-class-name="tableRowClassName"
                    :row-key="getRowKey"
                    highlight-current-row>
            <!-- <el-table-column v-if="enterprise === 1" type="selection" width="55" align="center" /> -->
            <el-table-column type="selection" width="40" align="center" :selectable="setDisabled" :reserve-selection="true"/>
            <el-table-column label="序号" type="index" width="50" align="center" prop="index" :index="indexMethod"
                             :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="企业名称" align="center" prop="enterpriseName" width="350" :show-overflow-tooltip="true"
                             v-if="columns[0].visible" />
            <el-table-column label="联系人" align="center" prop="contacts" width="150" v-if="columns[1].visible"
                             :show-overflow-tooltip="true" />
            <el-table-column label="联系电话" align="center" prop="telephone" :show-overflow-tooltip="true"
                             v-if="columns[2].visible" width="350" />
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList" />

        </el-col>
      </el-row>
      <!-- 图片预览 -->
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <!-- pdf预览 -->
      <el-dialog :visible.sync="dialogVisiblePdf" append-to-body>
        <pdf v-for="item in pageTotal" :src="pdfUrl" :key="item" :page="item"></pdf>
      </el-dialog>
      <el-dialog :title="titleClass" :visible.sync="openMainClass" width="500px" append-to-body>
        <el-form ref="formClass" :model="formClass" :inline="true">
          <el-form-item label="主分类" prop="classificationId" label-width="80px">
            <treeselect v-model="formClass.classificationId" :options="optionData" placeholder="请选择主分类"
                        style="width: 202.5px" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitClassForm()">确 定</el-button>
          <el-button @click="cancelClass">关 闭</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                   :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                   :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">关 闭</el-button>
        </div>
      </el-dialog>
      <select-user ref="select" :type="userType" :sign="sign" @ok="selectUser"></select-user>
      <el-row>
        <div v-if="open">
          <el-row>
            <el-col :span="24">

              <Operate @change="close" ref="operateref" :classId="classId" :opt="opt" :id="id" :obj="obj"
                       :newMarkAs="newMarkAs"></Operate>
            </el-col>
          </el-row>
        </div>
      </el-row>
    </div>
    <div v-if="type == 1">
      <Operate ref="operateref" @change="close" :classId="classId" :opt="edit" :id="id" :index="index"
               :newMarkAs="newMarkAs"></Operate>
    </div>



    <!-- <Operate ></Operate>   -->
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, editMainClass, editBusinessManager } from "@/api/enterprise/info";
import MainType from "@/components/MainType/index"
import { getToken } from "../../../utils/auth";
import SelectUser from "../../system/role/selectUser.vue"
import Operate from "./operate.vue"
import { listType } from "@/api/maintype/type";
import Treeselect from "@riophae/vue-treeselect";
import pdf from 'vue-pdf'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "sendAll",
  props: {
    markAs: {
      type: String,
      default: null
    },
    enterprise: {
      type: String,
      default: null
    },
    //选择企业的时候不能展示树节点的,同样，人员管理选择企业的时候，其他标签页不展示操作按钮
    isTree: {
      type: Boolean,
      default: true
    },
    //判断是否是通过活动培训管理/问卷调查管理 传过来的，是的话允许多选
    train: {
      type: Boolean,
      default: false
    },
    //判断是否是通过人员管理或者其他客户管理下面调用的，只是单纯的选择客户或者企业
    isEnterprise: {
      type: Boolean,
      default: false
    }
  },
  components: { MainType, Operate, SelectUser, Treeselect,pdf },
  dicts: ['enterprise_nature', 'customer_industry', 'enterprise_status'],
  data() {
    return {
      //pdf预览
      dialogImageUrl: '',
      dialogImageUrlPdf: '',
      pageTotal: null,
      dialogVisible:false,
      dialogVisiblePdf:false,
      refreshKey: 0,
      typeCode: 'enterprise',
      formClass: {},
      openMainClass: false,
      titleClass: "修改主分类",
      optionData: null,
      userType: "1",
      sign: '1',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      infoList: [],
      classId: null,
      //导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        newMarkAs: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/enterprise/info/importData?markAs=" + this.$route.query.markAs + ""
      },
      // 列信息
      columns: [
        { key: 0, label: `企业名称`, visible: true },
        { key: 1, label: `联系人`, visible: true },
        { key: 2, label: `联系电话`, visible: true },
        { key: 4, label: `公司编号`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `行政区域`, visible: true },
        { key: 7, label: `企业性质`, visible: true },
        { key: 8, label: `开户银行`, visible: true },
        { key: 9, label: `开户账号`, visible: true },
        { key: 10, label: `税号`, visible: true },
        { key: 11, label: `所属行业`, visible: true },
        { key: 12, label: `成立日期`, visible: true },
        { key: 13, label: `注册资金`, visible: true },
        { key: 14, label: `附件`, visible: true },
        { key: 15, label: `最新操作时间`, visible: true },
        { key: 16, label: `最新进展`, visible: true },
        { key: 17, label: `创建时间`, visible: true },
        { key: 18, label: `状态`, visible: true },
      ],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectionList: [],
      titleName: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        enterpriseName: null,
        enterpriseSource: null,
        enterpriseAbbreviation: null,
        administrativeArea: null,
        legalRepresentative: null,
        establishmentDate: null,
        contractAmount: null,
        enterpriseLabel: null,
        registeredCapital: null,
        industry: null,
        contacts: null,
        telephone: null,
        bankName: null,
        taxId: null,
        developmentId: null,
        transactionId: null,
        developmentManager: null,
        businessManager: null,
        enterpriseAddress: null,
        businessScope: null,
        enterpriseNature: null,
        markAs: null,
        belongTo: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        classificationId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
      },
      type: 0,
      opt: 'add',
      id: '',
      obj: null,
      index: null,
      edit: 'edit'
    };
  },
  created() {

    this.newMarkAs = this.$route.query.markAs
    if (this.$route.query.markAs == "1") {
      this.titleName = "客户管理信息数据"

    } else if (this.$route.query.markAs == "2") {
      this.titleName = "供应商管理信息数据"
    } else if (this.$route.query.markAs == "3") {
      this.titleName = "渠道管理信息数据"
    }
    if (Reflect.has(this.$route.query, "markAs")) {
      this.queryParams.markAs = this.$route.query.markAs
      //this.markAs = this.$route.query.markAs
    }
    if (this.markAs != null) {
      this.queryParams.markAs = this.markAs
    }
    if (this.train){
      this.columns[3].visible=false;
      this.columns[4].visible=false;
      this.columns[5].visible=false;
      this.columns[6].visible=false;
      this.columns[7].visible=false;
      this.columns[8].visible=false;
      this.columns[9].visible=false;
      this.columns[10].visible=false;
      this.columns[11].visible=false;
      this.columns[12].visible=false;
      this.columns[13].visible=false;
      this.columns[14].visible=false;
      this.columns[15].visible=false;
      this.columns[16].visible=false;
      this.columns[17].visible=false;
    }
    this.getList();
    this.listType();
  },
  methods: {
    //pdf预览
    handlePictureCardPreviewPdf(url) {
      this.pdfUrl = pdf.createLoadingTask(url)
      // 获取页码
      this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {
      })
      this.dialogImageUrlPdf = url;
      this.dialogVisiblePdf = true;
    },
    getRowKey (row) {
      return row.enterpriseId;
    },
    //文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    clearTable(){
      this.$refs.table.clearSelection();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.getList();
      this.upload.open = false;
    },
    handleImport() {
      this.upload.title = this.titleName + "导入";
      this.upload.open = true;
    },
    listType() {
      listType({ typeCode: 'enterprise' }).then(res => {
        this.optionData = res.data;
      })
    },
    //行点击事件
    handleCurrentChange(row, column, event) {
      //this.refreshKey++;
      //如果是从人员管理过来的，不展示详情数据

      if (this.isTree === true) {
        this.opt = 'details'
        this.obj = row
        this.id = row.enterpriseId;
        this.open = true
        this.$nextTick(() => {
          this.$refs.operateref.selectActiveName()
        })
      }
    },
    //当活动培训管理发送方访问的时候，如果用户自身的企业中有没有入驻的，不能让它进行选择
    setDisabled(row, index) {
      if (this.isTree === false && this.isEnterprise === false) {
        return row.settle;
      } else {
        return true;
      }
    },
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        console.log(response.rows)
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },

    cancelClass() {
      this.openMainClass = false;
      this.resetClass();
    },
    // 表单重置
    resetClass() {
      this.formClass = {
        classificationId: null,
      }
    },
    // 取消按钮
    cancel() {
      this.$emit("change")
    },
    submitForm() {
      if (this.selectionList.length == 0) {
        this.$modal.msgError("请选择客户");
      }
      if (this.train === false) {
        this.$emit("ok", this.selectionList[0])

      } else {
        this.$emit("ok", this.selectionList)
      }
      this.resetQuery();
      //this.$refs.table.clearSelection();
    },
    //索引初始化到对象
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + rowIndex + 1;
    },
    // 表单重置
    reset() {
      this.form = {
        enterpriseId: null,
        enterpriseName: null,
        enterpriseSource: null,
        enterpriseAbbreviation: null,
        administrativeArea: null,
        legalRepresentative: null,
        establishmentDate: null,
        contractAmount: null,
        enterpriseLabel: null,
        registeredCapital: null,
        industry: null,
        contacts: null,
        telephone: null,
        bankName: null,
        taxId: null,
        developmentId: null,
        transactionId: null,
        developmentManager: null,
        businessManager: null,
        enterpriseAddress: null,
        businessScope: null,
        enterpriseNature: null,
        markAs: null,
        belongTo: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        delFlag: null,
        classificationId: null

      };
      this.resetForm("form");
    },
    editMainClass() {
      if (this.ids.length == 0) {
        this.$message.error("请选择要修改的信息！");
      } else {
        this.openMainClass = true;
      }
    },
    userShow(type) {
      this.show = type
      if (type == "1") {
        if (this.ids.length == 0) {
          this.$message.error("请选择要修改的信息！");
        } else {
          this.$refs.select.show();
        }
      } else {
        this.$refs.select.show();
      }

    },
    submitClassForm() {
      if (this.formClass.classificationId == "undefined" || this.formClass.classificationId == "" || this.formClass.classificationId == null) {
        this.$message.error("请选择主分类！");
      } else {
        const params = {
          businessId: this.ids.toString(),
          mainClassId: this.formClass.classificationId,
        };
        editMainClass(params).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openMainClass = false;
          this.getList();
        });
      }
    },
    selectUser(userId, userName, phone, position) {
      if (this.show == '1') {
        const params = {
          businessId: this.ids.toString(),
          transactionId: userId,
          businessManager: userName
        };
        editBusinessManager(params).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        });
      } else if (this.show == '2') {
        this.$set(this.form, 'approvalName', userName)
        this.$set(this.form, 'approvalId', userId)
      }

    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.classificationId = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (this.markAs != null && this.train !== true) {
        this.selectionList = [];
        if (selection.length > 1) {
          this.$refs.table.clearSelection();
          this.$refs.table.toggleRowSelection(
            selection[selection.length - 1]
          );
        }
        this.selectionList = [selection[selection.length - 1]];
      } else {
       this.selectionList=selection;
        console.log(this.selectionList)
      }
      this.ids = selection.map(item => item.enterpriseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.edit = "add"
      this.type = 1

    },
    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.reset();
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index
      this.edit = "edit"
      this.id = row.enterpriseId;
      this.type = 1
      // const enterpriseId = row.enterpriseId || this.ids
      // getInfo(enterpriseId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改企业信息";
      // });
    },
    //树点击事件
    getNode(data, node, obj) {
      this.reset();
      //主分类

      //this.queryParams.cabinetId = data.id
      this.classId = data.id
      this.queryParams.classificationId = data.id
      this.getList()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const enterpriseIds = row.enterpriseId || this.ids;
      this.$modal.confirm('是否确认删除企业名称为"' + row.enterpriseName + '"的数据项？').then(function () {
        return delInfo(enterpriseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('enterprise/info/export', {
        ...this.queryParams
      }, this.titleName + "_" + new Date().getTime() + '.xlsx')
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/enterprise/info/importTemplate', {
      }, this.titleName + `.xlsx`)
    },
    close:function(data) {
      if(data==undefined){
        this.type = 0
        this.open = data;
      }
      this.getList();
    },
    //文件预览
    handleView(url) {
      if (url != null && url != '' && (url).indexOf('.pdf') !== -1) {
        this.handlePictureCardPreviewPdf(url);
      } else {
        this.handlePictureCardPreview(url);
      }
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
  }
};
</script>
<style scoped lang="scss">
.no-multiple {

  // 隐藏多选
  ::v-deep .el-table_2_column_20 .is-center .el-table-column--selection .is-leaf .el-table__cell {
    display: none;
  }
}
</style>
